package cn.favebook.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.dbutils.QueryRunner;

import cn.favebook.Global;
import cn.favebook.bean.User;
import cn.favebook.bean.Weibo;
import cn.favebook.db.WeiboDao;
//import jdk.nashorn.internal.runtime.JSONListAdapter;
//import sun.management.counter.perf.PerfByteArrayCounter;

/**
 * Servlet implementation class ListWeiboServlet
 */
@WebServlet("/zone/list.do")
public class ListWeiboServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		User currentUser = (User) request.getSession().getAttribute(Global.CURRENT_USER);
		if(currentUser == null) {
			response.sendRedirect("/favebook/signin.jsp");
		}
		String type = request.getParameter("type");
		if(type == null) {
			type = "html";
		}
		String pageNum = request.getParameter("page");
		int currentPage = 0;
		if (pageNum != null) {
			try {
				currentPage = Integer.valueOf(pageNum).intValue();
			} catch (NumberFormatException e) {
				e.printStackTrace();
				currentPage = 0;
			}
		}
		
		QueryRunner runner = (QueryRunner) request.getServletContext().getAttribute(Global.KEY_QUERY_RUNNER);
		List<Weibo> weibos = null;
		long count = 0;
		int perCount = 0;
		try {
			weibos = WeiboDao.find(runner, currentPage);
			count = WeiboDao.count(runner);
			perCount = (int) WeiboDao.perCount(runner, currentUser.getId());
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		
		long total = count % Global.PAGE_SIZE == 0 ? count / Global.PAGE_SIZE : 
			count / Global.PAGE_SIZE + 1;
		
		if(type.equals("html")) {
			request.setAttribute("articles", weibos);
			request.setAttribute("currentPage", currentPage);
			request.setAttribute("total", total);
			request.getRequestDispatcher("./list.jsp").forward(request, response);
		} else if(type.equals("json")) {
			response.setContentType("application/json; charset=utf8");
			JsonArrayBuilder builder = Json.createArrayBuilder();
			for(Weibo weibo : weibos) {
				builder.add(weibo.toJson());
			}
			builder.add(Json.createObjectBuilder().add("currentUserName", currentUser.getUsername()).add("currentUserEmail", currentUser.getEmail()).add("weiboCount", count).add("weiboPerCount", perCount));
			PrintWriter writer = response.getWriter();
			writer.print(builder.build().toString());
		}
	}


}
